package com.xuyiwei.mayi.service;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by xuyiwei on 2019/4/24.
 */
public class NormalSocketServer {
    public static void main(String[] args) throws IOException {
        NormalSocketServer.startSocket(8083);
    }

    public static void startSocket(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务端启动");
        while (true){
            Socket socket = serverSocket.accept();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream in = null;
                    BufferedReader br = null;
                    PrintWriter pw = null;
                    try {
                        StringBuffer sb = new StringBuffer();
                        sb.append(port+"接收到请求");
                        in = socket.getInputStream();
                        br = new BufferedReader(new InputStreamReader(in));
                        pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                        String str = null;
                        while (true) {
                            str = br.readLine();
                            if (str == null)
                                break;
                            System.out.println("Receive : " + str);
                            System.out.println("Hello, " + str);
                        }

                        pw.write("aaaa");
                        pw.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
        }

    }
}
